<template>
  <div>
    <AxiomSearchToolbar 
      :fields="searchFields" 
      :initial-query="props.searchQuery" 
      @search="handleSearch" 
    />
    <AxiomToolbar>
      <AxiomButton type="primary" icon="Upload" @click="handleUploadClick">上传新文档</AxiomButton>
      <AxiomButton type="danger" icon="Delete" :disabled="!selectedRows.length" @click="handleBatchDelete">
        批量删除
      </AxiomButton>
      <AxiomButton type="primary" icon="Refresh" :disabled="!selectedRows.length" @click="handleBatchIndex">
        批量索引
      </AxiomButton>
    </AxiomToolbar>

    <AxiomDataTable
      ref="dataTableRef"
      :data="documents"
      :columns="columns"
      :pagination="pagination"
      @selection-change="handleSelectionChange"
      @page-change="$emit('page-change', $event)"
      @size-change="$emit('size-change', $event)"
    >
      <template #file_name="{ row }">
        <AxiomGroup align="center" gap="small">
          <AxiomIcon :name="getFileIcon(row.file_name)" />
          <span>{{ row.file_name }}</span>
        </AxiomGroup>
      </template>

      <template #status="{ row }">
        <AxiomTag :type="getStatusType(row.status)" size="small">{{ getSingleStatusText(row.status) }}</AxiomTag>
      </template>
      
      <template #file_size="{ row }">
        <span>{{ formatSize(row.file_size) }}</span>
      </template>

      <template #actions="{ row }">
        <AxiomButton icon="Refresh" text @click="handleIndex(row)">索引</AxiomButton>
        <AxiomButton icon="Download" text @click="handleDownload(row)">下载</AxiomButton>
        <AxiomButton icon="Delete" text type="danger" @click="handleDelete(row)">删除</AxiomButton>
      </template>
    </AxiomDataTable>
    
    <input
      type="file"
      ref="fileInputRef"
      multiple
      class="d-none"
      :accept="acceptedFileTypes"
      @change="onFileSelected"
    />
  </div>
</template>

<script setup>
import { ref, computed, inject } from 'vue';
import { useRouter } from 'vue-router';
import {
  AxiomToolbar,
  AxiomButton,
  AxiomDataTable,
  AxiomIcon,
  AxiomTag,
  AxiomGroup,
  AxiomSearchToolbar,
} from 'axiom-view';
import { documentApi } from '@/api/knowledge/document.js';

const props = defineProps({
  documents: { type: Array, required: true },
  pagination: { type: Object, required: true },
  knowledgeBase: { type: Object, required: true },
  searchQuery: { type: Object, default: () => ({ file_name: '', status: null }) },
});

const emit = defineEmits(['refresh', 'page-change', 'size-change', 'search']);

const { notification, useConfirm } = inject('axiom-utils');
const { show: showConfirm } = useConfirm;
const router = useRouter();

const dataTableRef = ref(null);
const fileInputRef = ref(null);
const selectedRows = ref([]);

const statusMap = {
  0: { text: '未索引', type: 'info' },
  1: { text: '索引中', type: 'primary' },
  2: { text: '已索引', type: 'success' },
  3: { text: '错误', type: 'danger' },
};

const statusOptions = Object.entries(statusMap).map(([value, { text }]) => ({ 
  label: text, 
  value: Number(value) 
}));

const searchFields = ref([
  { model: 'file_name', label: '文件名', type: 'input', placeholder: '请输入文件名' },
  { 
    model: 'status', 
    label: '状态', 
    type: 'select', 
    options: statusOptions,
    multiple: false, // 修正：改为单选
    clearable: true, // 新增：允许用户清除选择
    placeholder: '请选择文档状态', // 优化：提供更清晰的占位符
    style: "width: 240px",
  },
]);

const acceptedFileTypes = '.txt,.md,.mdx,.pdf,.html,.xlsx,.xls,.docx,.csv,.vtt,.properties,.htm';

const columns = ref([
  { type: 'selection', width: 55 },
  { prop: 'file_name', label: '文件名', slot: 'file_name' },
  { prop: 'file_size', label: '大小', width: 120, slot: 'file_size' },
  { prop: 'status', label: '状态', width: 120, slot: 'status' },
  { prop: 'update_time', label: '更新时间', width: 180 },
  { prop: 'actions', label: '操作', width: 220, slot: 'actions', fixed: 'right' },
]);

function getSingleStatusText(status) {
  return statusMap[status]?.text || '未知';
}

function getStatusType(status) {
  return statusMap[status]?.type || 'info';
}

function formatSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
}

const fileIconMap = {
  pdf: 'document',
  doc: 'document',
  docx: 'document',
  xls: 'document',
  xlsx: 'document',
  ppt: 'document',
  pptx: 'document',
  txt: 'document',
  md: 'document',
  zip: 'folder',
  rar: 'folder',
  '7z': 'folder',
  default: 'document'
};

function getFileIcon(fileName) {
    const extension = fileName.split('.').pop().toLowerCase();
    return fileIconMap[extension] || fileIconMap.default;
}


function handleSelectionChange(selection) {
  selectedRows.value = selection;
}

// --- 搜索操作 ---
function handleSearch(query) {
  const cleanQuery = {
    file_name: query.file_name || '',
    // 修正：直接传递原始值 (number 或 null)
    status: query.status, 
  };
  emit('search', cleanQuery);
}

// --- 单个操作 ---
function handleIndex(row) {
  router.push({
    name: 'KnowledgeBaseIndexing',
    params: { kb_id: props.knowledgeBase.id },
    state: { documentIds: [row.id] }
  });
}

async function handleDelete(row) {
  await showConfirm({
    title: '确认删除',
    content: `您确定要删除文档 "${row.file_name}" 吗？`,
    type: 'danger',
    onConfirm: async () => {
      await documentApi.deleteDocument(row.id);
      notification.success({ title: '成功', message: '文档删除成功。' });
      emit('refresh');
    },
  });
}

function handleDownload(row) {
    // 假设 documentApi.downloadDocument 返回一个可供下载的 URL
    window.open(documentApi.getDownloadUrl(row.id), '_blank');
}

// --- 批量操作 ---
async function handleBatchDelete() {
  await showConfirm({
    title: '确认批量删除',
    content: `您确定要删除选中的 ${selectedRows.value.length} 个文档吗？`,
    type: 'danger',
    onConfirm: async () => {
      const ids = selectedRows.value.map(row => row.id);
      await documentApi.batchDeleteDocuments(ids);
      notification.success({ title: '成功', message: '批量删除成功。' });
      dataTableRef.value.clearSelection();
      emit('refresh');
    },
  });
}

function handleBatchIndex() {
  const ids = selectedRows.value.map(row => row.id);
  router.push({
    name: 'KnowledgeBaseIndexing',
    params: { kb_id: props.knowledgeBase.id },
    state: { documentIds: ids }
  });
}


// --- 上传逻辑 ---
function handleUploadClick() {
  fileInputRef.value.click();
}

function beforeUpload(file) {
  const isLt15M = file.size / 1024 / 1024 < 15;
  if (!isLt15M) {
    notification.error({ title: '上传错误', message: `文件 "${file.name}" 大小超过 15MB!` });
  }
  return isLt15M;
}

async function onFileSelected(event) {
  const files = Array.from(event.target.files).filter(beforeUpload);

  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }

  if (files.length === 0) return;

  const uploadToast = notification.info({
    title: '上传中',
    message: `正在上传 ${files.length} 个文件...`,
    duration: 0,
  });

  try {
    const res = await documentApi.batchUploadDocuments(props.knowledgeBase.id, files);
    
    uploadToast.close();
    
    // 假设API在成功时返回的数据中有成功和失败的详细信息
    // 这里我们简化处理，直接显示成功上传的数量
    const successCount = res.data?.length || files.length;
    const failCount = files.length - successCount;
    
    let summaryMessage = `上传完成。成功 ${successCount} 个`;
    if (failCount > 0) {
      summaryMessage += `，失败 ${failCount} 个。`;
    }
    notification.success({
      title: '上传结束',
      message: summaryMessage
    });
    
    if (successCount > 0) {
      emit('refresh');
    }
  } catch (error) {
    uploadToast.close();
    notification.error({
      title: '批量上传失败',
      message: `上传过程中发生错误: ${error.message}`
    });
  }
}
</script>

<style scoped>
</style>
